package lzm.code.lambdalearn.lambda.builtIn;

import lzm.code.lambdalearn.lambda.domain.Person;
import org.junit.jupiter.api.Test;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * <p> 内置四大函数接口  </p>
 *
 * @author liuziming
 * @description
 * @date 2023/12/20 8:51
 */
public class BuiltInFourFunctionInterfaces {


    /**
     * 消费型接口: Consumer< T> void accept(T t)有参数，无返回值的抽象方法；
     * 打印结果
     * hello,liu
     */
    @Test
    public void consumer_test() {
        Consumer<Person> consumer = p -> System.out.println("'hello," + p.getFirstName());
        consumer.accept(new Person("liu", "shanghai"));
    }

    /**
     * 供给型接口: Supplier < T> T get() 无参有返回值的抽象方法；
     * 打印结果
     * Person(firstName=null, lastName=null)
     */
    @Test
    public void supplier_test() {
        Supplier<Person> supplier = Person::new;
        Person person = supplier.get();
        System.out.println(person);
    }

    /**
     * 断定型接口: Predicate<T> boolean test(T t):有参，但是返回值类型是固定的boolean
     * <p>
     * resultA:true
     * resultA negate:false
     * resultB:false
     */
    @Test
    public void predicate_test() {
//        Predicate<String> predicate = (s) -> {
//            return s.length() > 3;
//        };
        Predicate<String> predicate = (s) -> s.length() > 3;
        boolean resultA = predicate.test("aaaa");
        System.out.println("resultA:" + resultA);
        boolean foo = predicate.negate().test("aaaa");// false
        System.out.println("resultA negate:" + foo);
        boolean resultB = predicate.test("b");
        System.out.println("resultB:" + resultB);
    }


    /**
     * 函数型接口: Function<T,R> R apply(T t)有参有返回值的抽象方法；
     * integer:4
     * apply1:123
     * apply:123
     */
    @Test
    public void function_test() {

        //String-->入参类型 Integer-->返回值类型
        Function<String, Integer> function = (s) -> s.length();
        Integer integer = function.apply("aaaa");
        System.out.println("integer:"+integer);

        Function<String, Integer> toInteger = Integer::valueOf;
        Integer apply1 = toInteger.apply("123");
        System.out.println("apply1:"+apply1);

        Function<String, String> backToString = toInteger.andThen(String::valueOf);
        String apply = backToString.apply("123");
        System.out.println("apply:"+apply);
    }

}
